# -*- coding:utf-8 -*-

class SqlUtils(object):
    """
    条件查询
    """

    def __init__(self):
        pass

    @classmethod
    def getOption(cls, conditions, fieldMap):
        option = '1=1 '
        for con in conditions:
            filed = fieldMap[con['field']]
            op = con['op']
            vaule = con['value']
            if (op == 'greater'):
                option += " and " + filed + " > '" + str(vaule) + "'"
            elif (op == 'notequal'):
                option += " and " + filed + " <> '" + str(vaule) + "'"
            elif (op == 'contains'):
                option += " and " + filed + " LIKE '%" + str(vaule) + "%'"
            elif (op == 'less'):
                option += " and " + filed + " < '" + str(vaule) + "'"
            elif (op == 'equal'):
                option += " and " + filed + " = '" + str(vaule) + "'"
        return option

    @classmethod
    def getWhereSentence(cls, fields, options, values):
        DBWhereSentence = []
        for (i, j, k) in zip(fields, options,
                             values):  # 组合生成SQL的where部分。zip函数会把参数组合成[(field[0],option[0],value[0]),(field[1],option[1],value[1]),(field[2],option[2],value[2])]这种格式
            if (j == 'LIKE '):
                DBWhereSentence.append(i + '  ' + j + ' ' + '\'' + "%" + str(k) + '%\'')
            else:
                DBWhereSentence.append(i + '  ' + j + ' \'' + str(k) + ' \'')  # 生成 filed[0] 空格 option[0] 空格 value[0]

        whereSentence = ' AND '.join(DBWhereSentence)  # 拼接多个条件
        return whereSentence

    @classmethod
    def getSortRule(cls, multiSort, fieldMap):
        sortFields = multiSort['field']
        sorts = multiSort['sort']
        sortField = []
        for i in sortFields:
            sortField.append(fieldMap[i])
        orderRule = []
        for (i, j) in zip(sortField, sorts):  # 同理，生成排序规则部分
            orderRule.append(i + ' ' + j)
        rule = ','.join(orderRule)  # 拼接排序规则
        return rule
